package com.crm.config;

import com.crm.pojo.Right;
import com.crm.pojo.Role;
import com.crm.pojo.User;
import com.crm.service.user.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.util.Set;

public class MyShiroRealm extends AuthorizingRealm {    //安全数据源
    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //redis中数据的key的前缀
    private String SHIRO_LOGIN_COUNT = "shiro_login_count"; //登录计数
    private String SHIRO_IS_LOCK = "shiro_is_lock"; //锁定用户登录

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用MyShiroRealm.doGetAuthenticationInfo获取身份信息!");

        //获取身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String userName = token.getUsername();

        User user = userService.login(userName);

        if (user == null) {
            throw new UnknownAccountException("账号错误");    //账号错误
        }

        if (user.getUsrFlag() == null || user.getUsrFlag().intValue() == 0) {
            throw new LockedAccountException("账号锁定");   //账号锁定
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user,   //身份
                user.getUsrPassword(),  //凭证
                ByteSource.Util.bytes("zp"),    //加密使用的salt
                getName()   //Realm对象的名称
        );

        //返回身份信息
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用MyShiroRealm.doGetAuthorizationInfo获取权限信息!");

        //获取权限信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //动态授权
        Role role = user.getRole();
        if (role != null) {
            info.addRole(user.getRole().getRoleName());
            System.out.println(user.getRole().getRoleName());
            Set<Right> rights = role.getRights();
            if (rights != null && rights.size() > 0) {
                for (Right right : rights) {
                    info.addStringPermission(right.getRightCode());
                }
            }
        }

        return info;
    }
}